<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    width="30%"
    @ok="handleSubmit"
    :maskClosable="false"
  >
    <BasicForm @register="registerForm" style="padding-top: 10px; padding-right: 30px" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { formConfigSchema } from './dictionary.data';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import {
    CreateDictionaryConfigParams,
    UpdateDictionaryConfigParams,
  } from '@/api/system/model/systemModel';

  import { addDictionaryConfig, updateDictionaryConfig } from '@/api/system/dictionary';

  import { useMessage } from '@/hooks/web/useMessage';
  import { useI18n } from '@/hooks/web/useI18n';

  defineOptions({ name: 'ButtonModal' });

  const emit = defineEmits(['success', 'register']);

  const { createMessage } = useMessage();
  const isUpdate = ref(true);
  let dicId: Number;

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 100,
    schemas: formConfigSchema,
    showActionButtonGroup: false,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    dicId = data.record?.id;
    if (!dicId) {
      dicId = data.dictionaryId;
    }

    if (unref(isUpdate)) {
      setFieldsValue({
        ...data.record,
      });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

  async function handleSubmit() {
    try {
      const { t } = useI18n();
      const values = await validate();
      setModalProps({ confirmLoading: true });
      // TODO custom api
      if (unref(isUpdate)) {
        let params: UpdateDictionaryConfigParams = {
          name: values['name'],
          code: values['code'],
          order_no: values['order_no'],
          remark: values['remark'],
        };
        const { code } = await updateDictionaryConfig(dicId, params);
        if (code == 0) {
          createMessage.success(t('sys.api.updateSuccess'), 1, () => {
            closeModal();
            emit('success');
          });
        } else {
          createMessage.error(t('sys.api.operationFailed'));
        }
      } else {
        let params: CreateDictionaryConfigParams = {
          name: values['name'],
          code: values['code'],
          order_no: values['order_no'],
          remark: values['remark'],
        };
        const { code } = await addDictionaryConfig(dicId, params);
        if (code == 0) {
          createMessage.success(t('sys.api.createSuccess'), 1, () => {
            closeModal();
            emit('success');
          });
        } else {
          createMessage.error(t('sys.api.operationFailed'));
        }
      }
    } catch (error) {
      console.log(error);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
